﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Data;
using System.Data.OleDb;

namespace m_pricelist._DAL_
{
    class CreateConnection
    {
        public string regPath { get; set; } 

        public CreateConnection()
        {
        }

        public CreateConnection(string newDb)
        {
            regPath = newDb;
        }

        public string getRegPath()
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.OpenSubKey(@"Software\VB and VBA Program Settings\Marel_Consulting\MFS_Pricelist", true);

            //TODO Finna aðraleið til að fá staðsettningu á db
            if (regPath.Contains("MarelPricelist.accdb") == true)
            {
                regPath.Replace("MarelPricelist.accdb", "");
            }

            return regPath;
        }

        public string getRegPath(string db)
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.OpenSubKey(@"Software\VB and VBA Program Settings\Marel_Consulting\MFS_Pricelist", true);
            regPath = regKey.GetValue(db).ToString();
            return regPath;
        }

        public DataSet ExecuteSql(string sql)
        {
            OleDbDataAdapter da;
            DataSet ds;

            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.OpenSubKey(@"Software\VB and VBA Program Settings\Marel_Consulting\MFS_Pricelist", true);

            if (regPath == null)
            {
                regPath = regKey.GetValue("DB").ToString();
            }

            OleDbConnection con = new OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0;data source =" + regPath + ";");

            //TODO skoða þetta
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }

            con.Open();
            da = new OleDbDataAdapter(sql, con);

            ds = new DataSet();
            da.Fill(ds);
            con.Dispose();
            da.Dispose();
            con.Close();
            return ds;
        }

    }
}
